/* 
 Project     : 48c6c450f1a4a0cc53d9585dc0fee742
 Created on  : Mar 16, 2013, 11:29:15 PM
 Author      : Truong Khuong - khuongxuantruong@gmail.com
 Description :
 Purpose of the stylesheet follows.
 */
if (typeof String.prototype.repeater !== 'function') {
    String.prototype.repeater = function(count) {var a = ""; for(x = 0; x < count; x++){a+=this} return a};
}
$.fn.serializeObject = function(){
    var o = {};
    var a = this.serializeArray();
    $.each(a, function() {
        if (o[this.name] !== undefined) {
            if (!o[this.name].push) {
                o[this.name] = [o[this.name]];
            }
            o[this.name].push(this.value || '');
        } else {
            o[this.name] = this.value || '';
        }
    });
    return o;
};
if (typeof String.prototype.endsWith !== 'function') {
    String.prototype.endsWith = function(str) {
        return this.slice(-str.length) === str;
    };
}
if (typeof String.prototype.startsWith !== 'function') {
    // see below for better implementation!
    String.prototype.startsWith = function(str) {
        return this.indexOf(str) === 0;
    };
}
isrunning = false;
PENDING = false;
function includejs(url) {
    try {
        var headID = document.getElementsByTagName("head")[0];
        var newScript = document.createElement('script');
        newScript.type = 'text/javascript';
        newScript.src = url;
        headID.appendChild(newScript);
        return;
        var _ui = document.createElement('script');
        _ui.type = 'text/javascript';
        _ui.src = url;
        var s = document.getElementsByTagName('script')[0];
        s.parentNode.insertBefore(_ui, s);
    } catch (e) {
    }
}
function includecss(url) {
    try {
        var headID = document.getElementsByTagName("head")[0];
        var cssNode = document.createElement('link');
        cssNode.type = 'text/css';
        cssNode.rel = 'stylesheet';
        cssNode.href = url;
        cssNode.media = 'screen';
        headID.appendChild(cssNode);
        return;
        var _ui = document.createElement('link');
        _ui.rel = 'stylesheet';
        _ui.type = 'text/javascript';
        _ui.href = url;
        var s = document.getElementsByTagName('link')[0];
        s.parentNode.insertBefore(_ui, s);
    } catch (e) {
    }
}
function checkStrength(password) {
    //initial strength
    var strength = 0;
    //if the password length is less than 6, return message.
    if (password.length < 6)
        return 0;
    //length is ok, lets continue.
    //if length is 8 characters or more, increase strength value
    if (password.length >= 6)
        strength += 1;
    //if password contains both lower and uppercase characters, increase strength value
    if (password.match(/([a-z].*[A-Z])|([A-Z].*[a-z])/))
        strength += 1;
    //if it has numbers and characters, increase strength value
    if (password.match(/([a-zA-Z])/) && password.match(/([0-9])/))
        strength += 1;
    //if it has one special character, increase strength value
    if (password.match(/([!,%,&,@,#,$,^,*,?,_,~])/))
        strength += 1;
    //if it has two special characters, increase strength value
    if (password.match(/(.*[!,%,&,@,#,$,^,*,?,_,~].*[!,%,&,@,#,$,^,*,?,_,~])/))
        strength += 1;
    //now we have calculated strength value, we can return messages
    //if value is less than 2
    return strength;
    if (strength === 1)
        return 'Weak';
    else if (strength === 2)
        return 'Fair';
    else if (strength === 3)
        return 'Good';
    else if (strength === 4)
        return 'Strong';
    else
        return 'Verry Strong';
}
function backendloading() {
    //$('#backendload').show();
    ShowLoadding();
}
function backendloaded() {
    //$('#backendload').hide();
    HideLoadding();

}
function ShowLoadding() {
    $("#loaddingbar").show();
    $("#loaddingbar div").stop(true).width(0).css({
        bottom: 1
    })
            .animate({
        width: '30%'
    }, 300)
            .animate({
        width: '50%'
    }, 600)
            .animate({
        width: '75%'
    }, 1200)
            .animate({
        width: '95%'
    }, 3000);
}
function HideLoadding() {
    $("#loaddingbar div").stop(true)
            .animate({
        width: '100%'
    }, 500, function() {
        $("#loaddingbar").stop().hide();
    });

}
function ErrorMsg(message) {
    bckdialog({
        message: message,
        type: 'error'
    }).open();
}
function WarningMsg(message) {
    bckdialog({
        message: message
    }).open();
}
function NoticeMsg(message) {
    bckdialog({
        message: message
    }).open();
}
function ConfirmMsg(_callback, _title, _btntitle) {
    if ($("#bckconfirmdialog").length === 0) {
        $('body').append('<div id="bckconfirmdialog"></div>');
    }
    $("#bckconfirmdialog").html('<p class="p-12">' + _title + '</p>').dialog({
        modal: true,
        //autoOpen        : option.autoOpen,
        width: 280,
        dialogClass: 'b-s-d-32 pie ',
        resizable: false,
        //width           :'auto',
        title: '<img class="p-a t-7 l-8" src="' + base_url + 'libraries/images/16/keyamoon/spam.png"/><span class="p-l-20">Confirm ?</span>',
        closeOnEscape: true,
        //hide                : "explode",
        buttons: [
            {
                text    :'Confirm',
                class   :'base_button base_red',
                click   : function() {
                    _callback();
                    $(this).dialog("close");
                }
            },{
                text    :'Cancel',
                class   :'base_button',
                click   : function() {
                    $(this).dialog("close");
                }
            }
        ]
    });
}
function bckdialog(_option) {
    var me = this;
    this.option = {
        modal:true,
        type: "notice", //notice,error,question,custom
        title: null,
        message: "",
        uidialog: $("#bckdialog"),
        icon: null,
        hideclose: false,
        autoOpen: false,
        minwidth: '320px',
        height: 'auto',
        dialogClass: '',
        proc_start: null,
        proc_end: null,
        onload: null,
        onclose: null,
        onopen: null,
        callback: null,
        buttons: null
    };
    var option = this.option;
    if (_option) {
        //$.map(_option,function(value,key){
        //	option[key]=value;
        //});
        $.each(_option, function(index, value) {
            option[index] = value;
        });
        this.option = option;
    }
    if ($("#bckdialog").length === 0) {
        $('body').append('\
        <span class="d-p-n">\
            <div id="bckdialog" class="p-20" title=" Notice Message !"></div>\
        </span>\
        ');
    }
    if (option.type === "notice") {
        if (option.icon === null)
            option.icon = "<img class='p-a t-7 l-8' src='" + base_url + "libraries/ui/themes/base/images/dialog_warning.png'/>";
        option.title = "<font class='p-l-20'> " + (option.title === null ? "Notice Message !" : option.title) + "</font>";
    } else if (option.type === "error") {
        if (option.icon === null)
            option.icon = "<img class='p-a t-7 l-8' src='" + base_url + "libraries/ui/themes/base/images/dialog_error.png'/>";
        option.title = "<font class='p-l-20 erc'> " + (option.title === null ? "Error Exception !" : option.title) + "</font>";
    }
    if (option.message === null || option.message === undefined) {
        //option.uidialog = $("#bckdialog");
    } else if (typeof(option.message) === "object") {
        option.uidialog = option.message;
    } else{ 
        if(!option.uidialog.is(":hidden")){
            var node=1;
            var $div=$('.ui-dialog-'+node);
            while($div.length>0 && !$div.is(":hidden")){
                node++;
                $div=$('.ui-dialog-'+node);
            }
            if($div.length===0){
                option.uidialog=$('<div/>',{
                    class:'ui-dialog-'+node
                }).before($('#bckdialog'));
            }
        }
        if (typeof(option.message) === "string") {
            option.buttons = {
                Close: function() {
                    $(this).dialog("destroy");
                }
            };
            //option.uidialog = $("#bckdialog");
            option.uidialog.html('<div class="p-20">' + option.message + '</div>');
        } else {
            //option.uidialog = $("#bckdialog");
            option.uidialog.html("Unkown this message !");
        }
    }
    return {
        open: function(str) {
            if (str) {
                option.uidialog.html('<div class="p-20">' + str + '</div>');
                option.buttons = {
                    Close: function() {
                        $(this).dialog("close");
                    }
                };
            }
            option.uidialog.dialog({
                modal: option.modal,
                /*autoOpen        : option.autoOpen,*/
                minwidth: option.minwidth,
                dialogClass: 'b-s-d-32 pie ' + option.dialogClass,
                resizable: false,
                width: 'auto',
                title: option.icon + option.title,
                closeOnEscape: true,
                /*hide                : "explode",*/
                buttons: option.buttons,
                open: function(event, ui) {
                    if (option.onopen && typeof(option.onopen) === "function") {
                        try {
                            option.onopen();
                        } catch (e) {
                        }
                    }
                    $(event.target).dialog('widget')
                            .css({position: 'fixed'})
                            .position({my: 'center', at: 'center', of: window});
                },
                close: function(event, ui) {
                    if (option.onclose && typeof(option.onclose) === "function") {
                        try {
                            option.onclose();
                        } catch (e) {
                        }
                    }
                },
                create: function() {
                    if (option.hideclose === true) {
                        $(this).closest(".ui-dialog")
                                .find(".ui-dialog-titlebar-close")
                                .hide();
                    }
                }
            });
        },
        close: function() {
            option.uidialog.dialog('close');
        }
    };
}
function backend(_option) {
    var option = {
        url: null,
        data: null,
        datatype: "json",
        proc_start: null,
        proc_end: null,
        callback: null
    };
    if (_option)
        $.each(_option, function(index, value) {
            option[index] = value;
        });
    if (option.datatype.toUpperCase() === 'JSON') {
        option.data.ajaxtype = 'json';
    }
    return {
        call: function(_url, _data, _callback) {
            if (isrunning === true)
                return;
            if (PENDING === true)
                return;
            if (_url)
                option.url = _url;
            if (_data)
                option.data = _data;
            if (_callback)
                option.callback = _callback;
            if (typeof(option.proc_start) === 'function')
                option.proc_start();
            else {
                backendloading();
            }
            PENDING = true;
            jQuery.ajax({
                type: "POST",
                //cache:false,
                //timeout:10000,
                data: option.data,
                dataType: option.datatype,
                url: option.url,
                success: function(data_result) {
                    isrunning = false;
                    PENDING = false;
                    if (typeof(option.callback) === 'function')
                        option.callback(data_result);
                    if (typeof(option.proc_end) === 'function')
                        option.proc_end();
                    else {
                        backendloaded();
                    }

                },
                error: function(xhr, ajaxOptions, thrownError) {
                    isrunning = false;
                    PENDING = false;
                    if (typeof(option.proc_end) === 'function')
                        option.proc_end();
                    else {
                        backendloaded();
                    }
                    if (typeof($.jGrowl) === 'function') {
                        $.jGrowl("Sorry. Your request could not be completed.<br/> Please check your input data and try again.", {sticky: true, theme: 'growl-error', header: 'Error!'});
                    }else {
                        //ErrorMsg("Sorry. Your request could not be completed.<br/> Please check your input data and try again.");
                        bckdialog({
                            message: "Sorry. Your request could not be completed.<br/> Please check your input data and try again.",
                            type: 'error'
                        }).open();
                    }
                }
            });
        }
    };
}
function BrowseServer(elementid){
    if ($(elementid).length === 0)
        ErrorMsg("Input element is not exist.");
    try {
        window.KCFinder = {};
        window.KCFinder.callBack = function(url) {
            window.KCFinder = null;
            $(elementid).val(url);
        };
        window.open(base_url + 'libraries/kcfinder/browse.php?lang=vi', 'kcfinder_textbox',
                'status=0, toolbar=0, location=0, menubar=0, directories=0, resizable=1, scrollbars=0, width=700, height=500'
                );
    } catch (e) {
        ErrorMsg(e.message);
    }
}
function addRedactorEditor(Element) {
    Element.redactor({
        //air: true,
        //wym: true,
        buttons: ['html', 'formatting', '|', 'bold', 'italic', 'deleted', '|', 'unorderedlist', 'orderedlist', 'outdent', 'indent', 'alignment', '|', 'video', 'link', '|', 'fontcolor', 'backcolor']
                ,
        plugins: ['advanced']
    });
}
function addEditorFeature(ElementID, height) {
    try {
        CKEDITOR.replace(ElementID, {
            toolbar: [
                    { name: 'document', groups: [ 'mode', 'document', 'doctools' ], items: [ 'Source', '-', 'Preview', '-', 'Templates' ] },
                    { name: 'editing', groups: [ 'find', 'selection', 'spellchecker' ], items: [ 'Find', 'Replace', '-', 'SelectAll', '-', 'Scayt' ] },
                    { name: 'insert', items: [ 'Image', 'Flash', 'Table', 'HorizontalRule', 'Smiley', 'SpecialChar', 'PageBreak', 'Iframe' ] },
                    
                    '/',
                    { name: 'basicstyles', groups: [ 'basicstyles', 'cleanup' ], items: [ 'Bold', 'Italic', 'Underline', 'Strike', 'Subscript', 'Superscript', '-', 'RemoveFormat' ] },
                    { name: 'paragraph', groups: [ 'list', 'indent', 'blocks', 'align', 'bidi' ], items: [ 'NumberedList', 'BulletedList', '-', 'Outdent', 'Indent', '-', 'Blockquote', 'CreateDiv', '-', 'JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock', '-', 'BidiLtr', 'BidiRtl', 'Language' ] },
                    { name: 'links', items: [ 'Link', 'Unlink', 'Anchor' ] },
                    
                    '/',
                    { name: 'styles', items: [ 'Styles', 'Format', 'Font', 'FontSize' ] },
                    { name: 'colors', items: [ 'TextColor', 'BGColor' ] },
                    { name: 'tools', items: [ 'Maximize', 'ShowBlocks' ] },
                    { name: 'others', items: [ '-' ] },
                    { name: 'about', items: [ 'About' ] }
            ],
            toolbarGroups :[
                    { name: 'document', groups: [ 'mode', 'document', 'doctools' ] },
                    { name: 'editing', groups: [ 'find', 'selection', 'spellchecker' ] },
                    
                    '/',
                    { name: 'basicstyles', groups: [ 'basicstyles', 'cleanup' ] },
                    { name: 'paragraph', groups: [ 'list', 'indent', 'blocks', 'align', 'bidi' ] },
                    { name: 'links' },
                    { name: 'insert' },
                    '/',
                    { name: 'styles' },
                    { name: 'colors' },
                    { name: 'tools' },
                    { name: 'others' },
                    { name: 'about' }
            ]

        });
    } catch (e) {
        ErrorMsg(e.message);
    }

}
function addEditorBasic(ElementID, height) {
    try {
        CKEDITOR.replace(ElementID, {
            toolbar: [
                ['Source','ShowBlocks','Templates'],
                ['Bold', 'Italic', '-', 'NumberedList', 'BulletedList','-','Outdent', 'Indent', '-', 'Link', 'Unlink'],
                ['JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock'],
                ['Font','FontSize', 'TextColor', 'BGColor']
            ]
        });
    } catch (e) {
        ErrorMsg(e.message);
    }
}
function openKCFinder(field_name, url, type, win) {
    try {
        tinyMCE.activeEditor.windowManager.open({
            file: base_url + 'libraries/kcfinder/browse.php?opener=tinymce&type=' + type,
            title: 'KCFinder',
            width: 700,
            height: 500,
            resizable: "yes",
            inline: true,
            close_previous: "no",
            popup_css: false
        }, {
            window: win,
            input: field_name
        });
    } catch (e) {
        ErrorMsg(e.message);
    }
    return false;
}
function proc_sart(elem) {
    $(".i-l-d", $(elem))
            .addClass("b-g-c-w-50")
            .show();

}
function proc_end(elem) {
    $(".i-l-d", $(elem))
            .removeClass("b-g-c-w-50")
            .fadeOut(500);

}
function islc(opt) {
    try {
        $(opt.element).multiselect({
            multiple: opt.multiple ? opt.multiple : false,
            header: opt.header ? opt.header : opt.filter ? opt.filter : false,
            noneSelectedText: opt.noneSelectedText ? opt.noneSelectedText : (opt.multiple ? "Select an Option" : "Select a Option"),
            selectedList: opt.selectedList ? opt.selectedList : 1,
            menuwidth: opt.menuwidth ? opt.menuwidth : null,
            minWidth: opt.minwidth ? opt.minwidth : 'auto', //$(opt.element).parent().width(),
            height: opt.height ? opt.height : 'auto',
            classes: opt.classes ? opt.classes : null,
            style: opt.style ? opt.style : null,
            biz: opt.biz ? opt.biz : null,
            beforeclose: function() {
                try {
                    if ($(this).hasClass("validate")) {
                        if ($(this).show().validationEngine('validate')) {
                            $(this).multiselect("option", {classes: opt.multiple ? '_mul erb' : null});
                        } else {
                            $(this).multiselect("option", {classes: opt.multiple ? '_mul' : null});
                        }
                        $(this).hide();
                    }
                } catch (e) {
                    ErrorMsg(e.message);
                }
            }
        });
        if (opt.filter)
            $(opt.element).multiselectfilter();
    } catch (e) {
        ErrorMsg(e.message);
    }
}
function BrowseServerCallBack(callback){
    try {
        window.KCFinder = {};
        window.KCFinder.callBack = function(url) {
            //url=url.replace(base_url+'0x4D/','');
            window.KCFinder = null;
            callback(url);
        };
        window.open(base_url + 'libraries/kcfinder/browse.php?lang=en', 'kcfinder_textbox',
                'status=0, toolbar=0, location=0, menubar=0, directories=0, resizable=1, scrollbars=0, width=700, height=500'
                );
    } catch (e) {
        ErrorMsg(e.message);
    }
}
function openKCFinderByPath(path,element){
	if ($(element).length === 0){
        alert("Input element is not exist.");
		return;
	}
	try {
		window.KCFinder = {};
		window.KCFinder.callBack = function(url) {
			window.KCFinder = null;
			$(element).val(url);
		};
		window.open(base_url + path, 'kcfinder_textbox',
				'status=0, toolbar=0, location=0, menubar=0, directories=0, resizable=1, scrollbars=0, width=700, height=500'
				);
	} catch (e) {
		alert(e.message);
	}
	
}
function openKCFinderMulti(callback) {
    window.KCFinder = {
        callBackMultiple: function(files) {
            window.KCFinder = null;
            callback(files);
        }
    };
    window.open(base_url + 'libraries/kcfinder/browse.php?lang=en',
            'kcfinder_multiple', 'status=0, toolbar=0, location=0, menubar=0, ' +
            'directories=0, resizable=1, scrollbars=0, width=800, height=600'
            );
}
function openKCFinderMultiByPath(path, callback) {
    window.KCFinder = {
        callBackMultiple: function(files) {
            window.KCFinder = null;
            callback(files);
        }
    };
    window.open(base_url + path,
            'kcfinder_multiple', 'status=0, toolbar=0, location=0, menubar=0, ' +
            'directories=0, resizable=1, scrollbars=0, width=800, height=600'
            );
}
function accessdenied() {
        bckdialog({
            title: '<font color="red">Access Denied</font>',
            icon: '<img class="p-a t-8 l-8 w-16 h-16" src="' + base_url + 'libraries/images/16/denied.png">',
            message: 'Access is denied.<br>This function to requires an administrative account.<br>Please check your authority, and try again.<br/><br/>\
                <a class="t-d-n" href="' + base_url + 'backend">&bull; Return home.</a><br/>\n\
                <a class="t-d-n" href="' + base_url + 'backend/auth/logout">&bull; Login with different user.</a><br/>'
        }).open();
}
function backend_update(fun, table, prefix, _id, _data, _callback) {
    backend({
        url: base_url + "backend/excution/update/" + fun + "/" + table + "/" + prefix + "/" + _id,
        data: _data,
        callback: function(rsdata) {
            if (rsdata.result < 0) {
                WarningMsg(rsdata.message);
            } else {
                NoticeMsg(rsdata.message);
                if (typeof(_callback) === 'function')
                    _callback(rsdata);
            }
        }
    }).call();
}
function backend_delete(_uri, _id, _callback) {
    if ($("#bckconfirmdialog").length === 0) {
        $('body').append('<div id="bckconfirmdialog"></div>');
    }
    $("#bckconfirmdialog").html('<p class="p-12">These items will be permanently deleted and cannot be recovered. Are you sure ?</p>')
    .dialog({
        modal: true,
        width: 280,
        dialogClass: 'b-s-d-32 pie ',
        resizable: false,
        title: '<img src="/libraries/images/16/Error (1).png"/> Delete Items ?',
        closeOnEscape: true,
        buttons: [
            {
                text    :'Delete',
                class   :'base_button base_red',
                click   : function() {
                    $("#bckconfirmdialog").parents('.ui-dialog').find('.dialog-pending').show();
                    backend({
                        url: _uri,
                        data: {Id: _id},
                        callback: function(rsdata) {
                            if (rsdata.result < 0) {
                                $.jGrowl(rsdata.message, {sticky: true, theme: 'growl-error', header: 'Error!'});
                            } else {
                                $.jGrowl(rsdata.message);
                                if (typeof(_callback) === 'function')
                                    _callback(rsdata);
                            }
                            $("#bckconfirmdialog").parents('.ui-dialog').find('.dialog-pending').hide();
                            $("#bckconfirmdialog").dialog("close");
                        }
                    }).call();
                }
            },{
                text    :'Cancel',
                class   :'base_button',
                click   : function() {
                    $(this).dialog("close");
                }
            }
        ]
    });
}
function destroy_parent(elem) {
    $(elem).parent().remove();
}
function AliasTo(from, element) {
  var str=$(from).val();
  str = str.replace(/^\s+|\s+$/g, ''); // trim
  str = str.toLowerCase();
  
  // remove accents, swap ñ for n, etc

  var from  = "àáạảãâầấậẩẫăằắặẳẵèéẹẻẽêềếệểễìíịỉĩòóọỏõôồốộổỗơờớợởỡùúụủũưừứựửữỳýỵỷỹđ·/_,:;";
  var to    = "aaaaaaaaaaaaaaaaaeeeeeeeeeeeiiiiiooooooooooooooooouuuuuuuuuuuyyyyyd-/_,:;";
  //var from = "àáäâèéëêìíïîòóöôùúüûñç·/_,:;";
  //var to   = "aaaaeeeeiiiioooouuuunc------";
  for (var i=0, l=from.length ; i<l ; i++) {
    str = str.replace(new RegExp(from.charAt(i), 'g'), to.charAt(i));
  }

  str = str.replace(/[^a-z0-9 -]/g, '') // remove invalid chars
    .replace(/\s+/g, '-') // collapse whitespace and replace by -
    .replace(/-+/g, '-'); // collapse dashes

  $(element).val( str );
}

function getImageSrc(src) {
    if (src.startsWith('/data/'))
        src = src.replace('/data/', '/data/thumbs/');
    return src;
}
$(document).ready(function() {
    if ($("#bckdialog").length === 0) {
        $('body').append('\
            <span class="d-p-n" style="display:none">\
                <div id="bckdialog" class="p-20" title="Notice Message !"></div>\\n\
                <div id="bckconfirmdialog" class="p-20" title="Confirm ?"></div>\
            </span>\
        ');
    }
    if ($("#loaddingbar").length === 0) {
        $('body').append('<div id="loaddingbar" class="loaddingbar"><div></div></div>');
    }
    $('body').uitooltip({
        //track: true,
        position: {
            my: "center bottom-5",
            at: "center top",
            using: function(position, feedback) {
                $(this).css(position);
                if ($(this).find('.arrow').length === 0) {
                    $("<div>")
                            .addClass("arrow")
                            .addClass(feedback.vertical)
                            .addClass(feedback.horizontal)
                            .appendTo(this);
                }
            }
        }
        
    });
});